<?php
namespace app\controller\model\apis;

use app\BaseController;
use app\controller\model;
use GuzzleHttp\Client;
use think\facade\Db;
class Hi extends BaseController
{
	public $urlTest="";
	public $develop=true;
	public $apiUrl="";
	protected $url='',$appKey,$secret,$supplierCode,$tables,$token;
	public $supplier;
	public $data;
	protected $header=["Content-Type" => "application/json"];
    public function __construct($supplier=[]){
	    $this->tables = new model\Tables();
		$this->start($supplier);
    }
	//加油的所有接口
	public function cancelOrder($supplier_no){
		$this->setData();
		$this->data['orderNo']=$supplier_no['supplier_no'];
		$re = $this->sendUrl('openapi/gasOrder/refund');
		if(isset($re['return_code']) && $re['return_code']=='000000'){
			return true;
		}
		return false;
	}
	public function mkOrder($order){
		$this->setData();
		if(!isset($order['order_no']) || strlen($order['order_no'])<1){
			$order['order_no'] = $order['service_no'];
		}
		$gas = DB::name($this->tables->gas)->where("id",$order['gasID'])->find();
		$this->data['gasNo']=$gas['gasID'];
		$this->data['oilNo']=trim($order['oil_no'],"#");//不带#号的
		$this->data['gunNo']=$order['oil_gun'];
		$this->data['orderNo']=$order['order_no'];
		$this->data['refuelingAmount']=$order['amount'];
		$this->data['userPhone']='13111111111';
		$re = $this->sendUrl('openapi/gasOrder/push');
		if(isset($re['return_code']) && $re['return_code']=='000000'){
			return true;
		}
		return $re['return_msg'];
	}
	public function returnOrder($order){
		$this->setData();
		$this->data['orderNo']=$order['supplier_no'];
		$re = $this->sendUrl('openapi/gasOrder/queryOrderDetail');
		if(isset($re['return_code']) && $re['return_code']=='000000'){
			return $re['return_data'];
		}
		return false;
	}
	public function getGas($gas){
		$this->setData();
		$this->data['gasNo']=$gas['gasID'];
		$re = $this->sendUrl('openapi/gas/queryGasInfoByGasNo');
		if(isset($re['return_code']) && $re['return_code']=='000000'){
			$this->addGas($re['return_data']);
			return true;
		}
		return false;
	}
	public function confirmOrder($supplier_no){
		return true;
	}
	public function pushGas($json){
		try {
			//接收上游推送油站更新通知
			$this->data = $json;
			if(is_string($json)) $this->data = json_decode($json,true);

			if($this->data){
				$sign = $this->data['sign'];
				$this->mkSign();
				if($sign != $this->data['sign']){
					w_log(0,"接口返回".$this->supplier['id'],"签名错误",'Hi/pushGas',json_encode($this->data));
					return '签名错误';
				}
				$this->addGas($this->data);
			}
			return '数据错误';
		}catch (\Exception $e){
			return '内部错误';
		}
	}
	public function pushOrder($json){
		try {
			//接收上游订单处理通知
			$this->data = $json;
			if(!is_array($json)) $this->data = json_decode($json,true);

			if($this->data){
				$sign = $this->data['sign'];
				$this->mkSign();
				if($sign != $this->data['sign']){
					$this->data['sign2']=$sign;
					w_log(0,"接口返回".$this->supplier['id'],"签名错误",'Hi/pushOrder',json_encode($this->data));
					return '签名错误';
				}
				return $this->data;
			}else{
				w_log(0,"接口返回".$this->supplier['id'],"数据错误",'Hi/pushOrder',json_encode($this->data));
				return '数据错误:2';
			}
		}catch (\Exception $e){
			w_log(0,"接口返回".$this->supplier['id'],"内部错误",'Hi/pushOrder',$e.error_get_last());
			return '内部错误';
		}
	}
	public function account(){
		$this->setData();
		$re = $this->sendUrl('openapi/account/queryAmount');
		if(isset($re['return_code']) && $re['return_code']=='000000'){
			return $re['return_data']['amount'];
		}
		return false;
	}
	public function getGasList($cint=1){
		//openapi/gas/queryList
		if($this->supplier['upPage']==0 && $this->supplier['upNum']>$cint)return false;
		if($this->supplier['upDate']==nowDate()){
			DB::name($this->tables->supplier)->where("id",$this->supplier['id'])->inc('upPage')->update();
			$this->supplier['upPage']++;
		}else{
			$this->supplier['upPage']=1;
			DB::name($this->tables->supplier)->where("id",$this->supplier['id'])->update(['upPage'=>1,'upDate'=>nowDate(),'upNum'=>1]);
		}
		$this->setData();
		$this->data['pageNum']=$this->supplier['upPage'];
		$this->data['pageSize']=100;
		$re = $this->sendUrl('openapi/gas/queryList');
//		print_r($re);
//		exit();
		if(isset($re['return_code']) && $re['return_code']=='000000'){
			if(!isset($re['return_data']['gasInfoList']) || count($re['return_data']['gasInfoList'])<1){
				DB::name($this->tables->supplier)->where("id",$this->supplier['id'])->update(['upPage'=>0,'upNum'=>$cint+1]);
			}
			foreach ($re['return_data']['gasInfoList'] as $v){
				$this->addGas($v);
			}
		}
		return false;
	}





	protected function addGas($v){
		$gas = DB::name($this->tables->gas)->where("gasID",$v['gasNo'])->find();
		$d=[
			'fromID'=>$this->supplier['id'],
			'gasID'=>$v['gasNo'],
			'name'=>$v['gasName'],
			'province'=>$v['provinceName'],
			'province_id'=>$v['provinceCode'],
			'city'=>$v['cityName'],
			'city_id'=>$v['countyCode'],
			'country'=>$v['countyName'],
			'address'=>$v['gasAddress'],
			'logo_small'=>$v['gasLogo'],
			'logo_big'=>$v['gasLogo'],
			'status'=>$v['gasStatus'],
			'lat'=>$v['gasAddressLatitude'],
			'lng'=>$v['gasAddressLongitude'],
		];
		if($gas){
			$up = DB::name($this->tables->gas)->where("id",$gas['id'])->update($d);
		}else{
			$up = DB::name($this->tables->gas)->insertGetId($d);
			$gas['id']=$up;
		}
		$up2=false;
		//处理价格和油枪
		$prices = $v['oilPriceList'];
		if($prices){
			//所有的油号全部禁用
			DB::name($this->tables->gasPrice)->where("gasID",$gas['id'])->update(['status'=>0]);
			$upPrice=false;
			foreach ($prices as $v2){
				//然后再挨着启用
				if (!$v2['gunNoList'] || count($v2['gunNoList'])<1){
					//没有枪号
					continue;
				}else{
					$price = DB::name($this->tables->gasPrice)->where("gasID",$gas['id'])->where("oil_no",$v2['oilNoName'])->find();
					$addUp=[
						'oil_type'=>$v2['oilType'],
						'oil_no'=>$v2['oilNoName'],
						'oil_name'=>$v2['oilNo'],
						'price_yfq'=>bcmul($v2['priceGun'],0.9,2),//嗨加油没有优惠价  不可思议般的存在
						'price_gun'=>$v2['priceGun'],
						'price_official'=>$v2['priceOfficial'],
						'status'=>1
					];
					$guns=[];
					foreach ($v2['gunNoList'] as $v3){
						$guns[] = ['gun_no'=>$v3];
					}
					$addUp['gun_nos']=json_encode($guns);
				}
				if($price){
					DB::name($this->tables->gasPrice)->where("id",$price['id'])->update($addUp);
					if($price['price_yfq']!=$addUp['price_yfq'] || $price['price_gun']!=$addUp['price_gun'] || $price['price_official']!=$addUp['price_official']){
						$upPrice=true;
					}
				}else{
					$addUp['gasID']=$gas['id'];
					DB::name($this->tables->gasPrice)->insertGetId($addUp);
				}
			}
			if($up  || $upPrice) DB::name($this->tables->gas)->where("id",$gas['id'])->inc('upNumber')->update();
		}
	}
	protected function setData(){
		$this->data = ['appId'=>$this->appKey] ;
	}
	protected function getToken(){
		$api = "api/v1/token";
		$re = $this->sendUrl($api,['channel_code'=>$this->appKey,'channel_key'=>$this->secret]);
		if($re && $re['code']==200){
			$this->supplier['token']=$re['data']['token'];
			$this->supplier['tokenTime']=time() + 7200;
			DB::name($this->tables->supplier)->update($this->supplier);
			return true;
		}else{
			return false;
		}
	}

	protected function start($supplier=[]){
		$this->supplier = $supplier;
		$this->apiUrl = $this->supplier['apiUrl'];
		$this->urlTest = $this->supplier['apiUrlTest'];
		if($this->supplier['develop']==-1) $this->develop=false;
		$this->develop?$this->url = $this->apiUrl:$this->url = $this->urlTest;
		$this->url = trim($this->url,"/")."/";
		$this->appKey = $this->supplier['appKey'];
		$this->secret = $this->supplier['secret'];
		$this->supplierCode = $this->supplier['supplierCode'];
		if($this->supplier['postType']==2){
			if($this->supplier['tokenTime']<time()){
				$this->getToken();
			}else{
				$this->token = $this->supplier['token'];
			}
		}
	}
	protected function mkSign(){
		if(isset($this->data['sign'])) unset($this->data['sign']);
		ksort($this->data);
		$str='';
		foreach ($this->data as $k=>$v){
			if($v!='' && $v!=null && $v!=[]){
				if(is_array($v)){
					foreach ($v as $k2=>$v2){
						if($v2!='' && $v2!=null && $v2!=[]){
							if($v2===true)$v2="true";
							if($v2===false)$v2="false";
							$str .= $k2."=".$v2."&";
						}
					}
				}else{
					if($v===true)$v="true";
					if($v===false)$v="false";
					$str .= $k."=".$v."&";
				}
			}
		}
		$str=trim($str,"&")."&key=".$this->secret;
		$this->data['sign']=strtoupper(md5($str));
	}
	protected function sendUrl($pra=''){
		if($pra=='') return [];
		$this->mkSign();
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL => $this->url.$pra,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_POSTFIELDS =>json_encode($this->data),
			CURLOPT_HTTPHEADER => array(
				'Content-Type: application/json'
			),
		));
		$response = curl_exec($curl);
		curl_close($curl);
		return json_decode($response,true);
	}
}
?>